package uk.ac.lkl.common.util;



import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * A converter that parses a <code>String</code> instance.
 * 
 * This class is typically used for automated conversion from
 * <code>String</code>s to wrapper classes. For example, converting a
 * <code>String</code> to a <code>Float</code> using
 * <code>Float.parseFloat()</code>.
 * 
 * <p>
 * <b>Problem:</b>Not all wrapper classes will work for this. e.g. parseInt
 * for Integer.
 * </p>
 * 
 * @author Darren Pearce
 * @version $Revision$
 * @version $Date$
 * 
 */
public class ParsingStringConverter<D> implements Converter<String, D> {

    /**
     * The method to use when converting <code>String</code>s.
     * 
     */
    private Method parsingMethod;


    public ParsingStringConverter(Class<D> cl) {
        try {
            parsingMethod = cl.getMethod("parse" + cl.getSimpleName(),
                    String.class);
        }
        catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(e);
        }
    }


    /**
     * Convert the specified <code>String</code> to an instance of class
     * <code>D</code>.
     * 
     * <p>
     * <b>Problem:</b>Exceptions need to be handled better. Shouldn't cause
     * RunTimeExceptions.
     * </p>
     * 
     * @param string
     *            the <code>String</code> to convert
     * 
     */
    public D convert(String string) {
        try {
            D result = (D) parsingMethod.invoke(null, string);
            return result;
        }
        catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

}
